package com.twelve.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.twelve.mapper.UserMapper;
import com.twelve.pojo.Data;
import com.twelve.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    private Result result = new Result();
    private Data data = new Data();
    @Autowired
    private UserMapper userMapper;
	//分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable  int currentPage,@PathVariable int pageSize) throws IOException {
        IPage<User> page=new Page<>(currentPage,pageSize);
        //2 执行分页查询
        IPage<User> userIPage = userMapper.selectPage(page, null);
        List<User> users = userIPage.getRecords();
        data.setRows(users);
        data.setTotalCount(users.size());
        result.setData(data);
        return result;
    }
    /**
     * 保存用户
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody  User user) {
        System.out.println(user+"  user--001");
        int insert = userMapper.insert(user);
        if(insert > 0){
            result.setCode(Code.SAVE_OK);
            result.setMsg("添加成功!");
        }else{
            result.setCode(Code.SAVE_ERR);
            result.setMsg("添加失败!");
        }
        return result;
    }

    /**
     * 根据用户id查询用户
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        int i = userMapper.deleteById(id);
        if(i > 0){
            result.setCode(Code.DELETE_OK);
            result.setMsg("删除成功!");
        }else{
            result.setCode(Code.DELETE_ERR);
            result.setMsg("删除失败!");
        }
        return result;
    }

    /**
     * 更新用户
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        int i = userMapper.updateById(user);
        if(i > 0){
            result.setCode(Code.DELETE_OK);
            result.setMsg("修改成功!");
        }else{
            result.setCode(Code.DELETE_ERR);
            result.setMsg("修改失败!");
        }
        return result;
    }

}
